<template>
    <div>
        <div class="m-b-10">
            <div class="f-medium m-b-5">
                <i class="fa fa-header m-r-5" aria-hidden="true"></i>计划标题
            </div>
            <el-input v-model="planTitle" placeholder="输入内容长度不得超过8个字符"></el-input>
            <span class="f-Esmall">你可以简要地描述本次航行计划的目的</span>
        </div>
        <div class="map-view">
            <ZMap ref="zmap" :initConfig="initConfig"></ZMap>
        </div>
        <div class="p-20">
            <div class="text-center m-b-10 f-medium">
                <i class="fa fa-map-marker m-r-10 text-c-blue"></i>
                设定巡航路线
            </div>
            <el-row :gutter="20" class="text-center m-b-10">
                <el-col :span="8">标序</el-col>
                <el-col :span="8">经度E</el-col>
                <el-col :span="8">纬度N</el-col>
            </el-row>
            <div v-for="(item, index) in posData" :key="index">
                <el-row :gutter="40" class="text-center m-b-10">
                    <el-col :span="8"><el-button size="mini" round type="primary" @click="toAddMarker(index + 1)">第{{ index
                        +
                        1
                    }}点</el-button></el-col>
                    <el-col :span="8">
                        <el-input v-model.number="item.lng" :placeholder="`第${index + 1}点经度`" size="mini"
                            @blur="reComputed(index)" :oninput="checkLng(posData[index], 'lng')"></el-input>
                    </el-col>
                    <el-col :span="8"><el-input v-model.number="item.lat" :placeholder="`第${index + 1}点纬度`" size="mini"
                            @blur="reComputed(index)" :oninput="checkLat(posData[index], 'lat')"></el-input></el-col>
                </el-row>
            </div>
        </div>
    </div>
</template>

<script>
import { initConfig } from '../config/map-config'
// 引入时间处理
import formatDate from "@/utils/formatData";
// 引入请求api
import { increasePlan, updateThePlan } from "@/api/planManage";
import checkLngLat from "@/mixins/checkLngLat";
export default {
    name: 'PlanForm',
    props: ['model'],
    mixins: [checkLngLat],
    data() {
        return {
            initConfig,
            markerIndex: "",
            planTitle: "",
            planId: "",
            posData: [
                { lng: "", lat: "" },
                { lng: "", lat: "" },
                { lng: "", lat: "" },
                { lng: "", lat: "" },
            ],
        }
    },
    methods: {
        // 对map组件的操作:传入要调用的函数名+参数
        op_map(fn, ...query) {
            return this.$refs.zmap[fn](...query)
        },
        // 打开编辑窗口
        editModel(item) {
            let { op_map } = this;
            this.planTitle = item.title;
            this.planId = item.id;
            let positions = item.positions;
            positions.forEach((poi, i) => {
                // 对输入框赋值
                this.posData[i].lng = poi.lng;
                this.posData[i].lat = poi.lat;
                op_map('addMarker', [{
                    options: {
                        extData: {
                            pointId: ++i,
                        },
                        position: [poi.lng, poi.lat],
                    },
                    showInfo: true,
                    icon: 'I' + i,
                    content: `第${i}点坐标为${poi.lng},${poi.lat}`
                }])
            });
            this.op_map('fitView')
        },
        // 点击添加锚点
        toAddMarker(index) {
            let zmap = this.$refs.zmap;
            this.markerIndex = index;
            zmap.map.setDefaultCursor("crosshair");
            zmap.contextMenu.removeItem("取消标记", this.closeMenu); //清除一次以免无限增多
            zmap.contextMenu.addItem("取消标记", this.closeMenu, 0); //右键菜单添加菜单项
            zmap.map.on("rightclick", this.rightClickMenu); //地图添加右键菜单
            zmap.map.on("click", this.clickListener); //地图添加点击生成标记
        },
        // 定义菜单项触发事件
        closeMenu() {
            let zmap = this.$refs.zmap;
            zmap.map.setDefaultCursor("pointer"); //鼠标恢复默认
            zmap.contextMenu.close(); //菜单关闭
            zmap.map.off("rightclick", this.rightClickMenu); //地图移除菜单事件
            zmap.map.off("click", this.clickListener); //地图移除添加标记
        },
        // 定义右键触发事件（出现菜单）
        rightClickMenu(e) {
            let zmap = this.$refs.zmap;
            zmap.contextMenu.open(zmap.map, e.lnglat);
            zmap.contextMenuPositon = e.lnglat;
        },
        // 定义点击添加标记事件
        clickListener(e) {
            let { op_map } = this;
            // 如果已经标记，则取消上一个标记
            const allMarkers = op_map("getA_Type", "marker");
            const MarkerIndex = this.markerIndex;
            let indexItem = allMarkers.filter(
                (item) => item.getExtData().pointId == MarkerIndex
            );
            if (indexItem.length) indexItem[0].setMap(null);
            // 添加新标记
            op_map('addMarker', [{
                options: {
                    position: [e.lnglat.KL, e.lnglat.kT],
                    extData: {
                        pointId: MarkerIndex,
                    },
                },
                showInfo: true,
                icon: 'I' + MarkerIndex,
                content: `第${MarkerIndex}点坐标为${e.lnglat}`
            }])
            // 给相应的输入框赋值获取坐标
            this.posData[MarkerIndex - 1].lng = e.lnglat.KL;
            this.posData[MarkerIndex - 1].lat = e.lnglat.kT;
            // 只能确定一个点，此后退出此状态
            this.closeMenu();
        },
        // 点击标记后出现信息窗口
        markerClick(e) {
            let infoWindow = new AMap.InfoWindow({ offset: new AMap.Pixel(0, -30) });
            infoWindow.setContent(e.target.content);
            infoWindow.open(this.map, e.target.getPosition());
        },
        // 定义菜单项触发事件
        closeMenu() {
            let zmap = this.$refs.zmap;
            zmap.map.setDefaultCursor("pointer"); //鼠标恢复默认
            zmap.contextMenu.close(); //菜单关闭
            zmap.map.off("rightclick", this.rightClickMenu); //地图移除菜单事件
            zmap.map.off("click", this.clickListener); //地图移除添加标记
        },
        //生成路线
        createLine() {
            let { op_map } = this;
            let zmap = this.$refs.zmap;
            // 清空之前添加的折线
            const allPolylines = op_map("getA_Type", "polyline");
            let route = allPolylines.filter(
                (item) => item.getExtData().lineType == "SetLine"
            );
            if (route.length) zmap.map.remove(route[0]);
            let path = [];
            // 获取所有的标记
            const markers = op_map("getA_Type", "marker");
            // 只获取路径标记，并给标记排序
            let Pathmarkers = markers.filter((item) => item.getExtData().id != 0);
            Pathmarkers = Pathmarkers.sort(
                (a, b) => a.getExtData().id - b.getExtData().id
            );
            // 判断是否有路径标记（不包括无人船标记）
            if (Pathmarkers.length > 1) {
                // 按顺序添加作为折线的折点
                Pathmarkers.map((item) => {
                    path.push([item._position[0], item._position[1]]);
                });
                // 形成闭环再次添加第一点标记
                path.push([Pathmarkers[0]._position[0], Pathmarkers[0]._position[1]]);
                // 设置折线实例的折点
                op_map('addPolyline', { path }, 'polylineStyle')
                op_map('fitView');
            } else {
                this.$Notify('当前地图标点无法生成路线！', 'warning');
            }
        },
        // 添加新计划或者修改计划
        addOrEditPlan() {
            let { op_map } = this;
            let planId = this.planId;
            let title = this.planTitle;
            let positions = this.posData;
            const mapMarker = op_map("getA_Type", "marker");
            // 判断提交的数据是否正确
            if (title == "" || mapMarker.length == 0) {
                this.$Notify('请把巡航计划填写完整！！', 'warning');
                return;
            }
            // 数据提交----编辑或者是新增计划
            if (this.model == "保留修改") {
                this.editPlanAjax(planId, title, positions);
            } else if (this.model == "添加") {
                this.addNewPlanAjax(title, positions);
            }
            // 处理完成后进行表格更新
            this.$store.dispatch("cruiseRecord/toGetPlansList");
        },
        // 编辑计划请求
        editPlanAjax(planId, title, positions) {
            let url = "planId=" + planId + "&title=" + title;
            positions = positions.filter((item) => item.lng != "" && item.lat != "");
            console.log("编辑请求发送：", url, JSON.stringify(positions));
            let data = { url, positions: JSON.stringify(positions) };
            updateThePlan(data)
                .then(() => {
                    this.closeDialog();
                    this.$Notify('计划修改已经保存');
                })
                .catch((err) => {
                    console.log(err, "提交失败");
                });
        },
        // 添加新计划请求
        addNewPlanAjax(title, positions) {
            let data = {};
            let stamp = new Date().getTime(); //精确到毫秒
            let setTime = formatDate(new Date());
            data.title = title;
            data.count = 0;
            data.time = setTime;
            data.type = "automatic";
            data.positionId = stamp;
            data.positions = positions.filter(
                (item) => item.lng != "" && item.lat != ""
            );
            increasePlan(JSON.stringify(data))
                .then(() => {
                    this.$store.dispatch("cruiseRecord/toGetPlansList");
                    this.closeDialog();
                    this.$Notify('您已新增一个计划');
                })
                .catch((err) => {
                    console.log(err);
                });
        },
        // 关闭窗口
        close() {
            // 恢复清空
            this.markerIndex = "";
            this.planTitle = "";
            this.planId = "";
            for (let k = 0; k < this.posData.length; k++) {
                this.posData[k].lng = "";
                this.posData[k].lat = "";
            }
            // 地图清空
            this.op_map('clear');
        },
        // 失去焦点的标记重定位
        reComputed(index) {
            let { op_map } = this;
            let zmap = this.$refs.zmap;
            const MarkerIndex = index + 1;
            let lng = this.posData[index].lng;
            let lat = this.posData[index].lat;
            const allMarkers = op_map('getA_Type', 'marker');
            let indexItem = allMarkers.filter(
                (item) => item.getExtData().pointId == MarkerIndex
            );
            if (lng && lat) {
                if (indexItem.length) indexItem[0].setMap(null);
                // 添加新标记
                op_map('addMarker', [{
                    options: {
                        position: [lng, lat],
                        // offset: new AMap.Pixel(-13, -30),
                        extData: {
                            pointId: MarkerIndex,
                        },
                    },
                    showInfo: true,
                    icon: 'I' + MarkerIndex,
                    content: `第${MarkerIndex}点坐标为${Number(lng).toFixed(6)},${Number(lat).toFixed(6)}`
                }])
            } else {
                // 如果输入框缺省经纬度的其中一个都会直接清除目标标记
                if (indexItem.length) zmap.map.remove(indexItem);
            }
            // 地图标点聚焦（适配窗口）
            op_map('fitView');
        },
    }
}
</script>
<style scoped lang="less">
/deep/ .amap-marker,
/deep/ .amap-icon,
/deep/ .amap-icon img {
    width: 32px !important;
    height: 32px !important;
}

.map-view {
    height: 500px;
}
</style>